package com.mega.common.core.exception.config;

import com.mega.common.core.domain.R;
import com.mega.common.core.enums.CommonMsgEnum;
import com.mega.common.core.exception.BusinessException;
import com.mega.common.core.exception.PreAuthorizeException;
import com.mega.common.core.i18n.msg.ServerExceptionMsgService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author mega
 */
@Slf4j
@RestControllerAdvice
@AllArgsConstructor
public class GlobalExceptionHandler {

    private final ServerExceptionMsgService serverExceptionMsgService;

    /**
     * @param e
     * @Description 处理所有业务异常
     * @Author Eric
     * @Date 2020年09月22日 13:23:19
     * @Return
     */
    @ExceptionHandler(BusinessException.class)
    R handleBusinessException(BusinessException e) {
        log.error(e.toString());
        return serverExceptionMsgService.getExceptionMessage(e);
    }

    /**
     * 未知错误
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    R Exception(Exception e) {
        log.error(e.getMessage(), e);
        return serverExceptionMsgService.getExceptionMessage(new BusinessException(CommonMsgEnum.SYSTEM_UNKNOWN_ERROR));
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public R validatedBindException(BindException e) {
        log.error(e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return R.fail(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object validExceptionHandler(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return R.fail(message);
    }

    /**
     * 权限异常
     */
    @ExceptionHandler(PreAuthorizeException.class)
    public ResponseEntity preAuthorizeException(PreAuthorizeException e) {
        log.error(e.toString());
        return new ResponseEntity(serverExceptionMsgService.getExceptionMessage(new BusinessException(CommonMsgEnum.FORBIDDEN)), HttpStatus.FORBIDDEN);
    }
}
